/**
 * LoginForm: 登录窗口逻辑组件
 */
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { actionCreators } from './store';
import { Redirect } from 'react-router-dom';

import { Message } from '@alifd/next';
import AuthForm from './AuthForm';

class LoginFrom extends PureComponent {
  static displayName = 'LoginFrom';
  static propTypes = {};
  static defaultProps = {};

  formChange = (value) => {
    console.log('formChange:', value);
  };

  handleSubmit = (errors, values) => {
    if (errors) {
      console.log('errors', errors);
      return;
    }
    console.log('values:', values.name, values.passwd);
    Message.success('登录成功');
    this.props.login(values.name, values.passwd);
    // 登录成功后做对应的逻辑处理
  };

  render() {
    const { loginStatus } = this.props;
    const config = [
      {
        label: '用户名',
        component: 'Input',
        componentProps: { placeholder: '用户名', size: 'large', maxLength: 20, },
        formBinderProps: { name: 'name', required: true, message: '必填', },
      },
      {
        label: '密码',
        component: 'Input',
        componentProps: { placeholder: '密码', htmlType: 'passwd', },
        formBinderProps: { name: 'passwd', required: true, message: '必填', },
      },
      {
        label: '登录',
        component: 'Button',
        componentProps: { type: 'primary', },
        formBinderProps: {},
      },
    ];

    const initFields = {
      name: '',
      passwd: '',
    };

    const links = [
      { to: '/#/register', text: '立即注册' },
      { to: '/forgetpassword', text: '找回密码' },
    ];

    if(!loginStatus) {
      return (
        <AuthForm
          title="登录"
          config={config}
          initFields={initFields}
          formChange={this.formChange}
          handleSubmit={this.handleSubmit}
          links={links}
        />
      );
    }else {
      return <Redirect to='/' />
    }
    
  }
}

const mapState = (state) => ({
  loginStatus: state.getIn(['login', 'login'])
});

const mapDispatch = (dispatch) => ({
  login(accoutElem, passwordElem) {
    console.log(accoutElem, passwordElem);
    dispatch(actionCreators.login(accoutElem, passwordElem));
  }
});

export default connect(mapState, mapDispatch)(LoginFrom);
